<template>
  <el-drawer
    v-model="visible"
    title="患者处方记录历史"
    direction="rtl"
    size="80%"
    @close="handleClose"
  >
    <div class="history-content">
      <!-- 患者信息 -->
      <div v-if="patientInfo" class="patient-info-card">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>患者信息</span>
            </div>
          </template>
          <el-descriptions :column="3" border>
            <el-descriptions-item label="姓名">333{{ patientInfo.patientName }}</el-descriptions-item>
            <el-descriptions-item label="性别">{{ patientInfo.gender === 1 ? '男' : '女' }}</el-descriptions-item>
            <el-descriptions-item label="年龄">{{ patientInfo.age }}岁</el-descriptions-item>
            <el-descriptions-item label="联系电话">{{ patientInfo.phone }}</el-descriptions-item>
            <el-descriptions-item label="身份证号">{{ patientInfo.idCardNumber }}</el-descriptions-item>
            <el-descriptions-item label="地址">{{ patientInfo.address }}</el-descriptions-item>
          </el-descriptions>
        </el-card>
      </div>

      <!-- 搜索表单 -->
      <div class="search-box">
        <el-form ref="elSearchFormRef" :inline="true" :model="searchInfo" class="demo-form-inline" @keyup.enter="onSubmit">
          <el-form-item label="创建日期">
            <el-date-picker
              v-model="searchInfo.createdAtRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">查询</el-button>
            <el-button @click="onReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 处方记录表格 -->
      <div class="table-box">
        <el-table
          v-loading="loading"
          :data="tableData"
          style="width: 100%"
          stripe
        >
          <el-table-column label="处方编号" prop="prescription_name" width="150" />
          <el-table-column label="开方日期" prop="CreatedAt" width="180">
            <template #default="scope">
              {{ formatDate(scope.row.CreatedAt) }}
            </template>
          </el-table-column>
          <!-- <el-table-column label="药品信息" prop="prescription_data" min-width="300">
            <template #default="scope">
              <div v-if="scope.row.prescription_data && scope.row.prescription_data.length > 0">
                <div v-for="(medicine, index) in scope.row.prescription_data" :key="index" class="medicine-item">
                  <span class="medicine-name">{{ medicine.medicineName }}</span>
                  <span class="medicine-spec">{{ medicine.specification }}</span>
                  <span class="medicine-quantity">× {{ medicine.quantity }}{{ medicine.unit }}</span>
                </div>
              </div>
              <span v-else>暂无药品信息</span>
            </template>
          </el-table-column> -->
       
          <!-- 单剂处方金额 --> 
          <el-table-column label="单剂处方金额" prop="price" width="120">
            <template #default="scope">
              ¥{{ scope.row.price?.toFixed(2) || '0.00' }}
            </template>
          </el-table-column>
          <el-table-column label="剂数" prop="ji" width="120">
            <template #default="scope">
              {{ scope.row.ji }}
            </template>
          </el-table-column>

          <el-table-column label="处方金额" prop="price" width="120">
            <template #default="scope">
              ¥{{ scope.row.total_price?.toFixed(2) || '0.00' }}
            </template>
          </el-table-column>


          <el-table-column label="操作" width="100" fixed="right">
            <template #default="scope">
              <el-button type="primary" link @click="viewDetail(scope.row)">
                查看详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="page"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>

      <!-- 处方详情抽屉 -->
      <el-drawer
        v-model="detailVisible"
        title="处方详情"
        direction="rtl"
        size="60%"
      >
        <div v-if="currentRecord" class="detail-content">
          <el-descriptions title="基本信息" :column="2" border>
            <el-descriptions-item label="处方名称">{{ currentRecord.prescription_name }}</el-descriptions-item>
            <el-descriptions-item label="开方日期">{{ formatDate(currentRecord.CreatedAt) }}</el-descriptions-item>
            <el-descriptions-item label="单剂处方金额">¥{{ currentRecord.price?.toFixed(2) || '0.00' }}</el-descriptions-item>
            <el-descriptions-item label="患者姓名">{{ currentRecord.patient_data?.patientName || '无' }}</el-descriptions-item>
            <el-descriptions-item label="剂">{{ currentRecord.ji }}</el-descriptions-item>  
            <el-descriptions-item label="总价">¥{{ currentRecord.total_price?.toFixed(2) || '0.00' }}</el-descriptions-item>  
          </el-descriptions>
          
          <div class="medicine-detail" style="margin-top: 20px;">
            <h3>药品明细</h3>
            <el-table :data="currentRecord.prescription_data" border>
              <el-table-column label="药品名称" prop="name" />
              <el-table-column label="数量类型" width="100">
                <template #default="scope">
                  {{ scope.row.quantityType === 'grams' ? '克' : scope.row.quantityType === 'bags' ? '包' : '千克' }}
                </template>
              </el-table-column>
              <el-table-column label="数量（克）" width="100">
                <template #default="scope">
                  {{ scope.row.quantityType === 'grams' ? scope.row.grams : 
                       scope.row.quantityType === 'bags' ? scope.row.bags : 
                       scope.row.kilograms }}
                </template>
              </el-table-column>
              <!-- <el-table-column label="单价" prop="price" width="100">
                <template #default="scope">
                  ¥{{ scope.row.price?.toFixed(4) || '0.0000' }}
                </template>
              </el-table-column> -->
             
             
              <el-table-column label="小计" width="100">
                <template #default="scope">
                  ¥{{ scope.row.totalPrice?.toFixed(2) || '0.00' }}
                </template>
              </el-table-column> 
            
            </el-table>
          
          
          </div>
        </div>
      </el-drawer>
    </div>
  </el-drawer>
</template>

<script setup>
import { getSysPrescriptionRecordList } from '@/api/system/sysPrescriptionRecord'
import { findSysPatients } from '@/api/system/sysPatients'
import { formatDate } from '@/utils/format'
import { ElMessage } from 'element-plus'
import { ref, watch, nextTick } from 'vue'

defineOptions({
  name: 'PrescriptionRecordHistory'
})

// Props
const props = defineProps({
  patientId: {
    type: [String, Number],
    default: null
  }
})

// 抽屉控制
const visible = ref(false)
const loading = ref(false)

// 患者信息
const patientInfo = ref(null)

// 表格数据
const tableData = ref([])
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)
const patientId = ref(0)
// 搜索条件
const searchInfo = ref({
  createdAtRange: null
})

// 处方详情抽屉
const detailVisible = ref(false)
const currentRecord = ref(null)

// 打开抽屉
const open = async (id) => {
  visible.value = true
  if (id) {
    console.log('patientId', id)
    patientId.value = id
    await loadPatientInfo()
    await getTableData()
    
  }
}

// 关闭抽屉
const handleClose = () => {
  visible.value = false
  resetData()
}

// 重置数据
const resetData = () => {
  patientInfo.value = null
  tableData.value = []
  page.value = 1
  total.value = 0
  searchInfo.value = {
    createdAtRange: null
  }
  detailVisible.value = false
  currentRecord.value = null
}

// 加载患者信息
const loadPatientInfo = async () => {
  try {
    if (!patientId.value) return
    const res = await findSysPatients({ ID: patientId.value })
    if (res.code === 0) {
      patientInfo.value = res.data.resysPatients
    }
  } catch (error) {
    console.error('加载患者信息失败:', error)
    ElMessage.error('加载患者信息失败')
  }
}

// 获取处方记录列表
const getTableData = async () => {
  if (!patientId.value) return
  console.log('patientId',patientId.value)
  loading.value = true
  try {
    const params = {
      page: page.value,
      pageSize: pageSize.value,
      patientId: patientId.value
    }
    
    // 添加时间范围筛选
    if (searchInfo.value.createdAtRange && searchInfo.value.createdAtRange.length === 2) {
      params.startCreatedAt = searchInfo.value.createdAtRange[0]
      params.endCreatedAt = searchInfo.value.createdAtRange[1]
    }
    
    const res = await getSysPrescriptionRecordList(params)
    if (res.code === 0) {
      // foreach res.data.list
      res.data.list.forEach(item => {
        item.patient_data = JSON.parse(item.patient_data)
        item.prescription_data = JSON.parse(item.prescription_data)
      })
      console.log('res.data.list',res.data.list)
      tableData.value = res.data.list || []
      
      total.value = res.data.total || 0
    }
  } catch (error) {
    console.error('获取处方记录失败:', error)
    ElMessage.error('获取处方记录失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const onSubmit = () => {
  page.value = 1
  getTableData()
}

// 重置搜索
const onReset = () => {
  searchInfo.value = {
    createdAtRange: null
  }
  page.value = 1
  getTableData()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  page.value = 1
  getTableData()
}

const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

// 查看详情
const viewDetail = (row) => {
  currentRecord.value = row
  detailVisible.value = true
}

// 暴露方法给父组件
defineExpose({
  open
})

</script>

<style scoped>
.history-content {
  padding: 20px;
}

.patient-info-card {
  margin-bottom: 20px;
}

.search-box {
  margin-bottom: 20px;
  padding: 16px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.table-box {
  background-color: white;
  border-radius: 4px;
  padding: 16px;
}

.medicine-item {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
}

.medicine-name {
  font-weight: bold;
  margin-right: 8px;
}

.medicine-spec {
  color: #666;
  margin-right: 8px;
  font-size: 12px;
}

.medicine-quantity {
  color: #409eff;
  font-size: 12px;
}

.pagination-wrapper {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

.detail-content {
  padding: 20px;
}

.medicine-detail h3 {
  margin-bottom: 16px;
  color: #303133;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
